package cmd

import (
	"fmt"
	"net/http"
	"os"
	"strings"

	"sysinfo/internal/collector"
	"sysinfo/internal/config"
	"sysinfo/internal/formatter"

	"github.com/gin-gonic/gin"
)

// ModuleRequest 模块请求结构
type ModuleRequest struct {
	Modules []string `json:"modules" binding:"required"`
}

// runAPIServer API服务器模式 - 提供HTTP JSON接口（使用Gin框架）
func runAPIServer() error {
	if cfg.APIPort < 1 || cfg.APIPort > 65535 {
		cfg.APIPort = 8000 // 默认端口
	}

	// 设置 Gin 模式
	gin.SetMode(gin.ReleaseMode)

	router := gin.New()

	// 添加中间件
	router.Use(gin.Recovery())
	router.Use(corsMiddleware())

	fmt.Fprintf(os.Stderr, "═══════════════════════════════════════════════════════════════\n")
	fmt.Fprintf(os.Stderr, "  API服务器模式已启动（Gin框架）\n")
	fmt.Fprintf(os.Stderr, "═══════════════════════════════════════════════════════════════\n")
	fmt.Fprintf(os.Stderr, "  服务器地址: http://localhost:%d\n", cfg.APIPort)
	fmt.Fprintf(os.Stderr, "  输出格式: JSON\n")
	fmt.Fprintf(os.Stderr, "  可用模块: system, cpu, memory, disk, network, process, smart, gpu, battery\n")
	fmt.Fprintf(os.Stderr, "═══════════════════════════════════════════════════════════════\n")
	fmt.Fprintf(os.Stderr, "\n")
	fmt.Fprintf(os.Stderr, "接口说明:\n")
	fmt.Fprintf(os.Stderr, "  POST /api/system-info - 获取系统信息\n")
	fmt.Fprintf(os.Stderr, "  请求体: {\"modules\": [\"cpu\", \"memory\", \"disk\"]}\n")
	fmt.Fprintf(os.Stderr, "  可用模块: all, system, cpu, memory, disk, network, process, smart, gpu, battery\n")
	fmt.Fprintf(os.Stderr, "\n按 Ctrl+C 停止服务器\n\n")

	// 注册API路由
	router.POST("/api/system-info", handleSystemInfo)

	// 启动服务器
	addr := fmt.Sprintf(":%d", cfg.APIPort)
	fmt.Fprintf(os.Stderr, "正在启动API服务器...\n")
	if err := router.Run(addr); err != nil {
		return fmt.Errorf("启动API服务器失败: %w", err)
	}

	return nil
}

// handleSystemInfo 处理系统信息请求
func handleSystemInfo(c *gin.Context) {
	var req ModuleRequest

	// 绑定请求体
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":   "无效的请求格式",
			"message": err.Error(),
		})
		return
	}

	// 验证模块参数
	if len(req.Modules) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "modules 参数不能为空",
		})
		return
	}

	// 创建配置
	apiConfig := &config.Config{
		Format:  "json",
		Modules: config.ModuleConfig{},
	}

	// 解析模块参数
	hasAll := false
	validModules := []string{"system", "cpu", "memory", "disk", "network", "ports", "process", "smart", "gpu", "battery"}

	for _, module := range req.Modules {
		module = strings.ToLower(strings.TrimSpace(module))
		if module == "all" {
			hasAll = true
			break
		}

		// 验证模块名称
		isValid := false
		for _, valid := range validModules {
			if module == valid {
				isValid = true
				break
			}
		}

		if !isValid {
			c.JSON(http.StatusBadRequest, gin.H{
				"error":         fmt.Sprintf("无效的模块名称: %s", module),
				"valid_modules": validModules,
			})
			return
		}

		// 设置对应的模块标志
		switch module {
		case "system":
			apiConfig.Modules.System = true
		case "cpu":
			apiConfig.Modules.CPU = true
		case "memory":
			apiConfig.Modules.Memory = true
		case "disk":
			apiConfig.Modules.Disk = true
		case "network":
			apiConfig.Modules.Network = true
		case "ports":
			apiConfig.Modules.Ports = true
		case "process":
			apiConfig.Modules.Process = true
		case "smart":
			apiConfig.Modules.SMART = true
		case "gpu":
			apiConfig.Modules.GPU = true
		case "battery":
			apiConfig.Modules.Battery = true
		}
	}

	// 如果包含 all，则启用所有模块
	if hasAll || (!apiConfig.Modules.System && !apiConfig.Modules.CPU && !apiConfig.Modules.Memory &&
		!apiConfig.Modules.Disk && !apiConfig.Modules.Network && !apiConfig.Modules.Ports && !apiConfig.Modules.Process &&
		!apiConfig.Modules.SMART && !apiConfig.Modules.GPU && !apiConfig.Modules.Battery) {
		apiConfig.Modules.All = true
	}

	// 收集系统信息
	info, err := collector.Collect(apiConfig)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "收集系统信息失败",
			"message": err.Error(),
		})
		return
	}

	// 格式化为JSON
	output, err := formatter.Format(info, apiConfig)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error":   "格式化输出失败",
			"message": err.Error(),
		})
		return
	}

	// 返回结果
	c.Header("Content-Type", "application/json; charset=utf-8")
	c.String(http.StatusOK, output)
}

// corsMiddleware CORS中间件
func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusOK)
			return
		}

		c.Next()
	}
}
